//
//  Bundle+SGExtension.swift
//  QingLiuSwift
//
//  Created by xyanl on 2024/11/14.
//  Copyright © 2024 考拉🐨. All rights reserved.
//

import UIKit

extension Bundle: SpadgerCompatible {}

public extension Spadger where Base: Bundle {
    
    /// 读取本地 json 文件
    /// - Parameters:
    ///   - fileName: 文件名
    ///   - type: 文件后缀名
    /// - Returns: description
    static func readJSONFile(_ fileName: String, _ type: String) -> Any? {
        if let path = Bundle.main.path(forResource: fileName, ofType: type) {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
                let jsonObject = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
                // 这里打印出解析后的JSON对象
                return jsonObject
            } catch {
                print("Error reading JSON file: \(error)")
                return nil
            }
        }

        return nil
    }
    
    /// 判断当前版本是否是第一次启动
    /// - Returns: 当前版本 > 上次记录的版本， true 是第一次启动
    static func isFirstLaunch() -> Bool {
        
        // 本地存储的版本号
        let version = UserDefaults.standard.string(forKey: "SGAppVersion") ?? ""
        // 当前版本
        let currentVersion = Bundle.sg.appVersion
        
        // 存储当前版本
        UserDefaults.standard.set(currentVersion, forKey: "SGAppVersion")
        UserDefaults.standard.synchronize()
        
        if version.isEmpty {
            // 没有记录，表示第一次启动
            return true
        }
        
        return currentVersion.sg.compareVesion(to: version) == 1
    }
}

// MARK: - 二、App的基本信息
public extension Spadger where Base: Bundle {
    
    /// App命名空间
    static var namespace: String {
        (Bundle.main.infoDictionary?["CFBundleExecutable"] as? String) ?? ""
    }
    

    /// 项目/app 的名字
    static var bundleName: String {
        (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? ""
    }
    
    /// 获取app的版本号
    static var appVersion: String {
        (Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String) ?? ""
    }
    
    /// 获取app的 Build ID
    static var appBuild: String {
        (Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String) ?? ""
    }
    
    /// 获取app的 Bundle Identifier
    static var appBundleIdentifier: String {
         Bundle.main.bundleIdentifier ?? ""
    }
    
    /// Info.plist
    static var infoDictionary: [String: Any]? {
        Bundle.main.infoDictionary
    }
    
    /// App 名称
    static var appDisplayName: String {
        (Bundle.main.infoDictionary!["CFBundleDisplayName"] as? String) ?? ""
    }
}
